package com.xiaoma.h5testdemo.common.utils

import android.net.Uri
import android.util.Log
import android.webkit.WebView
import android.webkit.WebViewClient

/**
 * author: liangjingbo
 * date: 2023/9/7
 * describe:
 */
object WebViewUtils {
    private val TAG = this.javaClass.simpleName + "_XMTag"
    private val notSupportSchemes = mutableListOf(
        "intent://",
        "file://",
        "data://",
        "market://",
        "tel://",
        "mailto://",
        "sms://",
        "javascript://",
        "shopeesg://",
        "whatsapp://",
        "baiduboxapp://"
    )

    private val supportSchemes = mutableListOf(
        "https://",
        "http://"
    )

    fun isWebViewNotSupportScheme(url: String?): Boolean {
        if (url.isNullOrEmpty()) return true
        for (notSupportScheme in notSupportSchemes) {
            if (url.contains(notSupportScheme, true)) {
                return true
            }
        }
        return false
    }

    fun isWebViewSupportScheme(url: String?): Boolean {
        if (url.isNullOrEmpty()) return true
        for (supportScheme in supportSchemes) {
            if (url.contains(supportScheme, true)) {
                return true
            }
        }
        return false
    }

    fun isNetErrorStatusCode(errorCode: Int): Boolean {
        Log.i(TAG, "isNetErrorStatusCode() errorCode:$errorCode")
        return WebViewClient.ERROR_HOST_LOOKUP == errorCode
                || WebViewClient.ERROR_CONNECT == errorCode
                || WebViewClient.ERROR_IO == errorCode
                || WebViewClient.ERROR_FAILED_SSL_HANDSHAKE == errorCode
                || WebViewClient.ERROR_TIMEOUT == errorCode
    }

    fun getWebViewCurrentUrl(webView: WebView?): String {
        val historyList = webView?.copyBackForwardList() ?: return ""
        // 获取当前页面的历史记录项
        val currentIndex = historyList.currentIndex
        val currentItem = historyList.getItemAtIndex(currentIndex) ?: return ""
        return currentItem.url
    }


    fun getUrlParams(url: String, paramsName: String): String? {
        return try {
            val uri = Uri.parse(url)
            uri.getQueryParameter(paramsName)
        } catch (e: Exception) {
            ""
        }
    }

}